﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Collections.ObjectModel;
using University.Workshop.Model;
namespace University.Workshop.DataAccess
{
    public class UserDataAccess
    {
        public const string ConnString = "Data Source=.\\sqlexpress; Initial Catalog=Pharmacy;Integrated Security=true";
        UserLogOn user = UserLogOn.Instance;
        
        public UserLogOn GetUserByUserName(string userName, string password)
        {
            string sqlSentence = "select * from [Person] where ID = @userName and Password=@Password";
            SqlConnection cnn = null;
            SqlConnection tempCnn = null;
           try
            {
                tempCnn = new SqlConnection(ConnString);
                cnn = tempCnn;
                cnn.Open();
                SqlCommand cmd = tempCnn.CreateCommand();
                cmd.CommandText = sqlSentence;
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.Parameters.AddWithValue("@userName", userName);
                cmd.Parameters.AddWithValue("@Password", password);
                SqlDataReader reader = cmd.ExecuteReader();
                if (!reader.HasRows)
                {
                    return null;
                }
                reader.Read();
                    user.Name=reader["Name"].ToString();
                    user.Surname1=reader["Surname_1"].ToString();
                    user.Surname2=reader["Surname_2"].ToString();
                    user.Address=reader["Address"].ToString();
                    user.Id=reader["Id"].ToString();
                    if (string.IsNullOrEmpty(reader["Telephone"].ToString()))
                        user.Telephone = 0;
                    else
                        user.Telephone=Convert.ToInt32(reader["Telephone"].ToString(), System.Globalization.CultureInfo.CurrentCulture);

                    if (string.IsNullOrEmpty(reader["Cellular"].ToString()))
                        user.Cellular = 0;
                    else
                        user.Cellular=Convert.ToInt32(reader["Cellular"].ToString(), System.Globalization.CultureInfo.CurrentCulture);
                    user.Occupation=reader["Ocupation"].ToString();
                    user.DateTimeEnter = DateTime.Now;
            return user;
            }
          
            finally {
                if (tempCnn != null)
                    tempCnn.Close();   
            }       
        }
    }
}